package com.wanlian.socketserver.Device;

import com.wanlian.json.JsonStringUtil;
import com.wanlian.socketserver.Device.worker.DeviceServerWorker;
import com.wanlian.util.HttpUtils;

/**
 * 设备上线or离线状态设置类
 */
public class DeviceOnlineChecker {
    private static String SET_ONLINE_URL = "http://localhost:8080/wanlian.candy/device/updonline";
    private static String SET_ONLINE_URL_LIST = "http://localhost:8080/wanlian.candy/device/updonline/list";


    private static void setOnlineByKeyAndState(String key, boolean online) {
        if (DeviceServerWorker.sessionPool.isRouterPeer(key)) {
            DeviceOnline deviceOnline = new DeviceOnline(key, online);
            HttpUtils.sendPost(SET_ONLINE_URL, JsonStringUtil.writeValueAsString(deviceOnline));
        }
    }

    private static void setOnlineByKeyAndState(String key, boolean online, String version) {
        if (DeviceServerWorker.sessionPool.isRouterPeer(key)) {
            DeviceOnline deviceOnline = new DeviceOnline(key, online, version);
            HttpUtils.sendPost(SET_ONLINE_URL, JsonStringUtil.writeValueAsString(deviceOnline));
        }
    }

    public static synchronized void setOnline(String key, String version) {
        setOnlineByKeyAndState(key, true, version);
    }

    public static synchronized void setOffline(String key) {
        setOnlineByKeyAndState(key, false);
        //System.out.println("off line key:" + key);
    }

    public static synchronized void setOnline(String key, boolean online) {
        setOnlineByKeyAndState(key, online);
    }
}
